package com.cnswhy.cloud.server.app.controller.notify;

import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.app.config.WxPayData;
import com.cnswhy.cloud.server.app.controller.BaseController;
import com.cnswhy.cloud.server.common.entity.enumeration.PayType;
import com.cnswhy.cloud.server.core.appservice.AppChargeMoneyService;
import com.cnswhy.cloud.server.core.appservice.AppSpellOrderService;
import com.cnswhy.cloud.server.core.entity.ShopOrder;
import com.cnswhy.cloud.server.core.service.ChargeMoneyService;
import com.cnswhy.cloud.server.core.service.shop.ShopOrderService;
import com.cnswhy.cloud.server.core.service.spell.BuyBackOrderService;
import com.cnswhy.cloud.server.core.service.spell.SpellOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

@RequestMapping("/wxNotify")
@Controller
@Slf4j
public class WxPayNotify extends BaseController {

    @Autowired
    private RedisService redisService;


    @Autowired
    private ShopOrderService shopOrderService;

    @Autowired
    private ChargeMoneyService chargeMoneyService;

    @Autowired
    private BuyBackOrderService buyBackOrderService;

    @Autowired
    private SpellOrderService spellOrderService;
    @Autowired
    private AppChargeMoneyService appChargeMoneyService;
    @Autowired
    AppSpellOrderService appSpellOrderService;


    @RequestMapping("/notify")
    @ResponseBody
    public String wxPaiNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.error("====================================微信支付回调");

        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultxml = new String(outSteam.toByteArray(), "utf-8");


        log.info(resultxml);
        SortedMap<String, String> doXMLParseWithSorted = doXMLParseWithSorted(resultxml);
        outSteam.close();
        inStream.close();
        try {
            // 验证成功 - 开始处理本地订单状态
            ProcessNotify(doXMLParseWithSorted, response, request);
        } catch (Exception ex) {
            // 若签名错误，则立即返回结果给微信支付后台
            WxPayData res = new WxPayData();
            res.SetValue("return_code", "FAIL");
            res.SetValue("return_msg", ex.getMessage());
            log.error("Sign check error : " + res.ToXml());
            response.getWriter().write(res.ToXml());
            response.getWriter().close();
        }

        return null;
    }

    public void ProcessNotify(SortedMap<String, String> params, HttpServletResponse response, HttpServletRequest request)
            throws IOException, Exception {
        try {
            // 支付状态
            String payCode = params.get("return_code").toString();
            System.out.println("订单状态：" + payCode);
            if (StringUtils.equals(payCode, "SUCCESS")) {
                String orderNo = params.get("out_trade_no").toString();
                System.out.println("订单号：" + orderNo);
                String attach = params.get("attach").toString();
                String totalAmount = params.get("total_fee");
                String tradeNo = params.get("transaction_id");
                BigDecimal orderPrice = BigDecimal.ZERO;
                //ShopOrder queryByOrderNo = shopOrderService.getOne(Wraps.<ShopOrder>lbQ().eq(ShopOrder::getChannelOrderId,orderNo));
                //ShopOrder queryByOrderNo = shopOrderService.getOne(Wraps.<ShopOrder>lbQ().eq(ShopOrder::getPayOrderNo,orderNo));
                //orderPrice = queryByOrderNo.getOrderPrice();
                // 订单金额一致，判断订单状态
                if("UPGRADE".equals(attach)){
                    appSpellOrderService.upgradeOrder(tradeNo, orderNo, PayType.wx);
                } else {
                    appSpellOrderService.saveOrderNotify(orderNo, tradeNo);
                }

            }

        } catch (Exception e) {
            log.error("回调失败", e);
        }
        WxPayData res = new WxPayData();
        res.SetValue("return_code", "SUCCESS");
        res.SetValue("return_msg", "OK");
        response.getWriter().write(res.ToXml());
        response.getWriter().close();

    }


    public static SortedMap<String, String> doXMLParseWithSorted(String strxml) throws Exception {
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
        if (null == strxml || "".equals(strxml)) {
            return null;
        }

        SortedMap<String, String> m = new TreeMap<String, String>();
        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }

            m.put(k, v);
        }

        //关闭流  
        in.close();
        return m;
    }

    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if (!children.isEmpty()) {
            Iterator it = children.iterator();
            while (it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if (!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }
        return sb.toString();
    }
}
